var express = require('express');
var router = express.Router();
const SMSClient = require('@alicloud/sms-sdk')
/* GET users listing. */

let { userModel } = require('../model/model.js')




function getCode() {
    let str = '';
    const codeLength = 6; // 可以自定义验证码长度
    for (let i = 0; i < codeLength; i++) {
        str += Math.floor(Math.random() * 10).toString(); // 获取0 - 9的随机数并转换为字符串
    }
    return str;
}


// router.get('/list', async (req, res) => {
//     let list = await userModel.find()
//     res.send({
//         code: 200
//     })
// })

router.post('/get_sms', function (req, res, next) {
    let phoneNum = req.body.phone
    console.log('手机号码', phoneNum)
    //初始化sms_client
    let smsClient = new SMSClient({
        accessKeyId: 'LTAI5tJxVUUYXmDoEiC9WQy7',
        secretAccessKey: 'QESrLIdGte35cuwkkh5qKaqHhTIgtS'
    })
    let str = getCode()
    console.log(str);

    //开始发送验证码
    smsClient.sendSMS({
        PhoneNumbers: phoneNum,
        SignName: '旅游App',
        TemplateCode: "SMS_474806325",
        TemplateParam: `{"code":'${str}'}`
    }).then(result => {
        console.log('result', result)
        let { Code } = result
        if (Code == 'OK') {
            res.json({
                code: 0,
                msg: 'success',
                sms: str
            })
            console.log(result)
        }
    }).catch((err) => {
        console.log(err);
        res.json({
            code: 1,
            msg: "fail : " + err.data.Message
        })
    })
})

//修改手机号，并发送验证码
router.post('/update_phone', async (req, res) => {
    let newPhoneNum = req.body.new_phone; // 获取新手机号
    let phoneNum = req.body.phone; // 获取原手机号
    let list = await userModel.find({ phone: phoneNum })
    console.log('原手机号码', phoneNum);
    console.log('新手机号码', newPhoneNum);
    let smsClient = new SMSClient({
        accessKeyId: 'LTAI5tJxVUUYXmDoEiC9WQy7',
        secretAccessKey: 'QESrLIdGte35cuwkkh5qKaqHhTIgtS'
    })
    let str = getCode()
    smsClient.sendSMS({
        PhoneNumbers: newPhoneNum,
        SignName: '旅游App',
        TemplateCode: "SMS_474806325",
        TemplateParam: `{"code":'${str}'}`
    }).then(result => {
        console.log('result', result);
        let { Code } = result;
        if (Code == 'OK') {
            list[0].phone = newPhoneNum
            list[0].save()
            res.json({
                code: 0,
                msg: 'success',
                sms: str
            });
        }
    }).catch((err) => {
        console.log(err);
        res.json({
            code: 1,
            msg: "fail : " + err.data.Message
        });
    });
})
//对应手机号
router.get('/phone', async (req, res) => {
    let { name } = req.query
    let list = await userModel.find({ username: name })
    console.log(list);

    let phone = list[0].phone
    res.send({
        code: 200,
        phone
    })
})

module.exports = router;